import Taro from '@tarojs/taro'

import { View, PageContainer, Textarea, Input, Text, Image, Picker } from '@tarojs/components'
import { AtButton } from 'taro-ui'
import { useReducer, useState } from 'react'

import { hideLoading, reducer, showLoading, showModal, showToast } from '../../utils'

import './index.scss'
import TypeSelector from './typeSelector'
import XImage from '../../components/XImage'
import { uploadApi } from '../../services/Upload'
import { publishApi } from '../../services/Vote'

export default () => {
    let maxImageSize = 5 //最大图片 5 M
    let [showSelectType, setshowSelectType] = useState(true)
    let contentMaxLength = 200
    let optionMaxLength = 30
    let [formData, formDataDispatch] = useReducer(reducer, {
        type : 1,
        content : '',
        options : [],
        expireIn : ''
    })
    function selectType(type:number) {
        formDataDispatch({type : type})
        setshowSelectType(false)
    }

    function addOption() {
        let options:any[] = formData.options
        options.push({avatar : '', text : ''})
        formDataDispatch({options : [...options]})
    }
    function deleteOption(index:number) {
        let options:any[] = formData.options
        options.splice(index, 1)
        formDataDispatch({options : [...options]})
    }
    function inputOption(text:string, index:number) {
        let options:any[] = formData.options
        options[index].text = text
        formDataDispatch({options : [...options]})
    }


    async function selectAvatar(index:number) {
        let options:any[] = formData.options
        let res = await Taro.chooseImage({
            count: index == -1 ? 9 : 1,
        })

        if(index == -1) {
            for(let i = 0; i < res.tempFiles.length; i ++) {
                let file = res.tempFiles[i]
                if(file.size > maxImageSize * 1024 * 1024) {
                    showToast(`图片不能超过${maxImageSize}M`)
                    return
                }

                options.push({avatar : file.path})
            }
        }else {
            let file = res.tempFiles[0]
            if(file.size > maxImageSize * 1024 * 1024) {
                showToast(`图片不能超过${maxImageSize}M`)
                return
            }
            options[index].avatar = file.path

            // uploadApi(file.path).then(res => {
            //   console.log(res)
            // })
        }

        formDataDispatch({options : [...options]})

    }

    async function confirm() {
        if(formData.content === '') {
            showToast('请填写投票内容')
            return
        }
		const voteType = formData.type
		
        let params:{content:string, type : number, options:{image:string,text:string}[], expireIn:string} = {
			type : voteType,
            content : formData.content,
            expireIn : formData.expireIn,
            options : []
        }

        let tempFiles:any[] = []
        for(let i = 0; i < formData.options.length; i ++) {
            let option = formData.options[i]
            if(voteType == 1 || voteType == 3) {
                if(option.avatar == '') {
                    showToast('请选择图片')
                    return
                }
            }

            if(voteType != 3) {
                if(option.text === '') {
                    showToast('请填写选项内容')
                    return
                }
            }
            tempFiles.push(option.avatar)
            params.options.push({image : '', text : option.text})
        }

        showLoading()

        if(voteType == 1 || voteType == 3) {
            for(let i = 0; i < tempFiles.length; i ++) {
                let res = await uploadApi(tempFiles[i])
                params.options[i].image = res.data
            }
        }

        
        let res = await publishApi(params)
        if(res.success) {
            Taro.redirectTo({
                url : '/pages/vote/index?id=' + res.data
            })
        }else {
            console.log(res)
            showModal(res.msg)
        }

        hideLoading()

    }

    return <>
            <View className='p-l-r'>
                <View className='m-t-30 relative'>
                    <Textarea className='content' placeholder='关于你的一些想法的东西' maxlength={contentMaxLength} onInput={e => { formDataDispatch({content : e.detail.value}) }}></Textarea>
                    <View className='strlength'>{formData.content.length}/{contentMaxLength}</View>
                </View>

                <View className='m-t-30 f-36'>投票选项</View>

                <View className='m-t-30'>
                    {formData.type == 1 &&
                        formData.options.map((option, index) => {
                            let Avatar = () => {
                                return option.avatar
                                        ? <View key={index} className='h-100 bc-fff' style='border-radius:50%;'>
                                            <Image style='border-radius:50%;height:100%;' mode='scaleToFill' src={option.avatar}></Image>
                                        </View>
                                        : <></>
                            }

                            return <View className='row'>
                                <View className='flex-align-items-center'>
                                    <View className='avatar' onClick={() => selectAvatar(index)}>
                                        <Avatar></Avatar>
                                    </View>
                                    <Input className='option-input flex-1 m-l-20' value={option.text} maxlength={optionMaxLength} onInput={e => { inputOption(e.detail.value, index) }} />
                                </View>
                                <View className='text-right'>
                                    {formData.options.length > 2 &&
                                        <Text className='color-f56c6c' onClick={() => { deleteOption(index) }}>删除</Text>
                                    }
                                    <Text className='color-999 m-l-20'>{option.text.length}/{optionMaxLength}</Text>
                                </View>
                            </View>
                        })
                    }

                    {formData.type == 2 &&
                        formData.options.map((option, index) => <View className='row'>
                            <View>
                                <Input className='option-input' value={option.text} maxlength={optionMaxLength} onInput={e => { inputOption(e.detail.value, index) }} />
                            </View>
                            <View className='text-right m-t-10'>
                                {formData.options.length > 2 &&
                                    <Text className='color-f56c6c' onClick={() => deleteOption(index) }>删除</Text>
                                }
                                <Text className='color-999 m-l-20'>{option.text.length}/{optionMaxLength}</Text>
                            </View>
                        </View>)
                    }





                    {formData.type == 3 &&

                        <View className='option-grid'>
                            {
                                formData.options.map((option, index) => {
                                    return <View className='item'>
                                        <View className='close' onClick={() => deleteOption(index) }></View>
                                        <View className='wrap'>
                                            <Image className='h-100' mode='scaleToFill' src={option.avatar} />
                                        </View>
                                    </View>
                                })
                            }

                            <View className='item' onClick={() => selectAvatar(-1)}>
                                <View className='wrap'>
                                    <XImage className='addgrid xy' src='jia.png'></XImage>
                                </View>
                            </View>
                        </View>

                    }


                </View>

                {(formData.type == 1 || formData.type == 2) &&
                    <View className='m-t-30'>
                        <View onClick={addOption}>新增选项</View>
                    </View>
                }

            </View>

            <View className='m-t-30 p-l-r'>
                <Picker mode='date' onChange={e => formDataDispatch({expireIn : e.detail.value}) }>
                    <View className='expire-row'>
                        <Text>有效期限：</Text>
                        <Text className='pull-right'>{formData.expireIn}</Text>
                    </View>
                </Picker>
            </View>

            <View className='m-t-30 p-l-r'>
                <AtButton type='primary' circle onClick={confirm}>发 布</AtButton>
            </View>


            <PageContainer show={showSelectType} position='center'>
                <TypeSelector onSelect={type => { selectType(type) }}></TypeSelector>
            </PageContainer>
    </>
}
